//base
import Taro, { Component } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import { AtActionSheet } from 'taro-ui'
//redux
import { connect } from '@tarojs/redux'
import { DOREQUESTWORKEXP, DOEDITWORKEXP } from './store/actions/pageworkexp'
import { CLEARPAGEWORKEXP, UPDATEPAGEWORKEXP } from './store/types/pageworkexp'
import { UPDATEPAGECHOOSEJOBINPUT } from '../../pages/choose-job-input/store/types/pagechoosejobinput'

//less
import './index.less'

import NetworkError from '../../components/taro-ui/network-error'
import MessageSelectSingle from '../../components/page-components/message-select-single'
import { deepCopy } from '../../util/lodashmin'
import MessageInputWrap from '../../components/page-components/message-input-wrap'
import BtmFixedBtn from '../../components/page-components/btm-fixed-btn'
import BtnFixedDelete from '../../components/page-components/btn-fixed-delete'
import { hideLoading, showLoading, showToast } from '../../crossplatform/apiservice/toast'
import { navigateBack, navigateTo } from '../../crossplatform/apiservice/navigate'
import { putDeleteWorkExperienceRequest } from '../../service/user-archive-controller'
import pagejumplist from '../../configuration/pagejumplist.json'
import { judyCanLight } from '../../util/pagemethods/judyThings'
import If from '../../components/page-components/if'
import Dialog from '../../components/page-components/dialog'

const mapActiontoProps = dispatch => ({
  updateState(payload) {
    dispatch({
      type: UPDATEPAGEWORKEXP,
      payload: {
        ...payload
      }
    })
  },
  editWorkExp(payload) {
    DOEDITWORKEXP(payload).then(({ status, message }) => {
      hideLoading()
      if (status) {
        showToast({
          title: '编辑成功！'
        })
        setTimeout(() => {
          navigateBack()
        }, 500)
      } else {
        showToast({
          title: message || '编辑失败！'
        })
      }
    })
  },
  createWorkExp(payload) {
    DOREQUESTWORKEXP(payload).then(data => {
      hideLoading()
      const status = data.status
      const message = data.message
      if (status) {
        showToast({
          title: '创建成功！'
        })
        setTimeout(() => {
          navigateBack()
        }, 500)
      } else {
        showToast({
          title: message || '创建失败！'
        })
      }
    })
  },
  updateJobInput(payload) {
    dispatch({
      type: UPDATEPAGECHOOSEJOBINPUT,
      payload: {
        ...payload
      }
    })
  },
  clearState(payload) {
    dispatch({
      type: CLEARPAGEWORKEXP
    })
  }
})

@connect(
  ({ pageworkexp, pagechoosejobinput, userinfo, pagenewworkexp }) => ({
    ...pageworkexp,
    jobinput: pagechoosejobinput.inputData,
    zhichuUserId: userinfo.zhichuUserId,
    workExp: pagenewworkexp.workExp,
    userId: userinfo.userId
  }),
  mapActiontoProps
)
class WorkExp extends Component {
  constructor(props) {
    super(props)
    this.state = { modalVisible: false }
  }

  config = {
    navigationBarTitleText: '工作经历'
  }

  componentWillMount() {
    //onLoad
    let params = this.$router && this.$router.params
    if (params.id) {
      let singledata = {}
      this.props.workExp.forEach(data => {
        if (data.id == params.id) {
          singledata = data
        }
      })
      this.setInitData(singledata)
      this.props.updateState({
        cant: false
      })
    } else {
      const nowMonth = new Date().getMonth() + 1
      const nowYear = `${new Date().getFullYear()}-${nowMonth >= 10 ? nowMonth : '0' + nowMonth}`
      this.props.updateState({
        cant: true,
        workTimeWrap: {
          value: '2015-01',
          fields: 'month',
          mode: 'date'
        },
        workTimeWrapEnd: {
          value: nowYear,
          fields: 'month',
          mode: 'date'
        }
      })
    }

    this.setState({
      modalVisible: false
    })
  }

  componentDidMount() {
    //onready
  }

  componentDidShow() {
    //onshow
    this.doOnShowInput && this.doOnShowInput()
    this.doOnShowInput = null
  }

  componentDidHide() {
    //onhide
  }

  componentWillUnmount() {
    //onUnload
    this.props.clearState()
  }

  queryWrap = () => {}

  onReload = () => {
    this.queryWrap()
  }

  dorequest = () => {
    this.props.dorequest()
  }

  setInitData = singledata => {
    let workTimeWrapdeep = deepCopy(this.props.workTimeWrap || [])
    let workTimeWrapEnddeep = deepCopy(this.props.workTimeWrapEnd || [])
    workTimeWrapdeep.value = singledata.beginTime.replace('.', '-')
    workTimeWrapEnddeep.value = singledata.endTime.replace('.', '-')
    let params = {
      submitdata: {
        jobtitle: singledata.jobtitle,
        jobintro: singledata.workcontent,
        companyname: singledata.cpname
      },
      workTimeWrap: workTimeWrapdeep,
      workTimeWrapEnd: workTimeWrapEnddeep
    }
    this.props.updateState({
      ...params
    })
  }

  onSelectChange = ({ type, value }) => {
    if (type == 'worktime') {
      let workTimeWrap = deepCopy(this.props.workTimeWrap)
      workTimeWrap.value = value
      this.props.updateState({
        workTimeWrap: workTimeWrap
      })
    } else if (type == 'worktimeend') {
      let workTimeWrapEnd = deepCopy(this.props.workTimeWrapEnd)
      workTimeWrapEnd.value = value
      this.props.updateState({
        workTimeWrapEnd: workTimeWrapEnd
      })
    }
    this.judyCanLight()
  }

  doOnShowInput = null
  onInputChange = ({ type, value, name, componenttype, maxLength, tip }) => {
    this.doOnShowInput = () => {
      let submitdata = deepCopy(this.props.submitdata)
      submitdata[type] = this.props.jobinput.value
      this.props.updateState({
        submitdata
      })
      this.judyCanLight()
    }
    this.props.updateJobInput({
      inputData: { type, value, name, componenttype, maxLength, tip }
    })
    navigateTo({
      url: `${pagejumplist['choose-job-input'].path}`
    })
  }

  onInputCompanyChange = ({ type, value, name, componenttype, maxLength, tip }) => {
    this.doOnShowInput = () => {
      let submitdata = deepCopy(this.props.submitdata)
      submitdata[type] = this.props.jobinput.value
      this.props.updateState({
        submitdata
      })
      this.judyCanLight()
    }
    this.props.updateJobInput({
      inputData: { type, value, name, componenttype, maxLength, tip }
    })
    navigateTo({
      url: `${pagejumplist['choose-job-input'].path}?pageType=company`
    })
  }

  formatData = ({ submitdata, workTimeWrap, workTimeWrapEnd }) => {
    const { zhichuUserId } = this.props
    let submitFormat = {
      positionName: submitdata.jobtitle,
      achievement: submitdata.jobintro,
      companyName: submitdata.companyname,
      beginTime: workTimeWrap.value + '-01 00:00:00',
      endTime: workTimeWrapEnd.value + '-01 00:00:00',
      userId: zhichuUserId
    }
    return submitFormat
  }

  judyCanLight = () => {
    const { submitdata, workTimeWrap, workTimeWrapEnd, companyWrap } = this.props
    const result = this.formatData({ submitdata, workTimeWrap, workTimeWrapEnd, companyWrap })
    let expect = {
      achievement: '',
      beginTime: '',
      companyName: '',
      endTime: '',
      positionName: ''
    }
    let canlight = judyCanLight(result, expect)
    this.props.updateState({
      cant: !canlight
    })
  }

  submit = () => {
    showLoading()
    const { submitdata, workTimeWrap, workTimeWrapEnd, companyWrap } = this.props
    const submitFormatData = this.formatData({
      submitdata,
      workTimeWrap,
      workTimeWrapEnd,
      companyWrap
    })
    if (!this.jugdyResult(submitFormatData)) {
      // 数据格式失败  重新填写
      return
    }
    let { id } = this.$router.params
    if (id) {
      this.props.editWorkExp({
        id,
        userId: this.props.userId,
        ...submitFormatData
      })
    } else {
      this.props.createWorkExp({
        ...submitFormatData
      })
    }
  }

  jugdyResult = result => {
    // 检测数据问题
    const { beginTime, endTime } = result
    const nowMonth = new Date().getMonth() + 1
    const nowYear = `${new Date().getFullYear()}-${nowMonth >= 10 ? nowMonth : '0' + nowMonth}`
    if (beginTime > endTime) {
      showToast({
        title: '开始时间不能大于结束时间'
      })
      return false
    } else if (beginTime > nowYear) {
      showToast({
        title: '不能大于当前年份'
      })
      return false
    }
    return true
  }

  onDelete = () => {
    // 点击删除按钮
    this.setState({
      modalVisible: true
    })
  }

  onDeleteCancel = () => {
    this.setState({
      modalVisible: false
    })
  }

  onDeleteOk = () => {
    const { id } = this.$router.params
    console.log(this.$router.params, 'deleteWorkExperience')
    const { workExp } = this.props
    if (workExp && workExp.length > 1) {
      showLoading()
      putDeleteWorkExperienceRequest({ id }).then(({ data }) => {
        hideLoading()
        if (data.status) {
          // 删除成功 返回上一个页面
          showToast({
            title: '删除成功'
          })
          setTimeout(() => {
            navigateBack()
          }, 500)
        } else {
          showToast({
            title: data.message || '删除失败'
          })
        }
      })
    } else {
      this.setState({
        modalVisible: false
      })
      showToast({
        title: '当前为最后一条工作经历， 无法删除'
      })
    }
  }

  delay(time = 0) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve()
      }, time)
    })
  }

  render() {
    const { id } = this.$router.params
    const { workExp } = this.props
    const { modalVisible } = this.state
    return (
      <View className="WorkExp_id35351">
        <NetworkError visible={this.props.networkerror} onReload={this.onReload} />
        <View className={`WorkExp_id35351Wrap ${this.props.networkerror ? 'hide' : ''}`}>
          <View className="title">工作经验</View>
          <MessageInputWrap
            name="公司名称"
            type="companyname"
            value={this.props.submitdata.companyname}
            tip="*支持全国所有公司名称"
            onChange={this.onInputCompanyChange}
            maxLength="46"
          />
          <MessageInputWrap
            name="工作职位"
            type="jobtitle"
            value={this.props.submitdata.jobtitle}
            tip="*公司组织架构的岗位名称"
            onChange={this.onInputChange}
            maxLength={8}
          />
          <MessageSelectSingle
            name="开始时间"
            type="worktime"
            fields="month"
            value={this.props.workTimeWrap.value}
            mode={this.props.workTimeWrap.mode}
            onChange={this.onSelectChange}
            fields={this.props.workTimeWrap.fields}
          />
          <MessageSelectSingle
            name="结束时间"
            type="worktimeend"
            fields="month"
            value={this.props.workTimeWrapEnd.value}
            mode={this.props.workTimeWrapEnd.mode}
            onChange={this.onSelectChange}
            fields={this.props.workTimeWrap.fields}
          />
          <MessageInputWrap
            name="工作描述"
            type="jobintro"
            componenttype="textarea"
            value={this.props.submitdata.jobintro}
            tip="*不能填联系方式以及特殊符号"
            onChange={this.onInputChange}
            maxLength={2000}
          />

          <If visible={!id}>
            <BtmFixedBtn text="保存" onTap={this.submit} cant={this.props.cant} />
          </If>
          <If visible={id}>
            <BtnFixedDelete
              leftText={`${workExp && workExp.length > 1 ? '删除' : ''}`}
              rightText="保存"
              onDelete={this.onDelete}
              onTap={this.submit}
              cant={this.props.cant}
            />
          </If>

          <AtActionSheet isOpened={modalVisible}>
            <Dialog
              title="删除工作经历"
              subtext="您确定要删除此段工作经历吗？"
              leftText="取消"
              rightText="确认"
              onOk={this.onDeleteOk}
              onLeftOk={this.onDeleteCancel}
            />
          </AtActionSheet>
        </View>
      </View>
    )
  }
}

export default WorkExp
